/* global chrome,XMLHttpRequest */
var ifm = null
var port = null
chrome.identity.onSignInChanged.addListener((account, signedIn) => {
  console.log(account)
  console.log(signedIn)
})
window.onload = function () {
  ifm = document.getElementById('boxFrame')
  setSize()
  window.addEventListener('message', receiveMessage)
  runtime()
}
window.onresize = function () {
  setSize()
}
function setSize () {
  ifm.height = document.documentElement.clientHeight
}

function runtime () {
  port = chrome.runtime.connect({name: '$tcp'})
  port.onMessage.addListener(function (msg) {
    sendMessage({
      type: 'msg',
      data: msg
    })
  })
  sendMessage({
    type: 'connect'
  })
}

function receiveMessage (event) {
  var type = event.data.type
  var data = event.data.data
  chrome.runtime.sendMessage({
    'type': type,
    'data': data
  }, function (result) {
    sendMessage({
      'type': type,
      data: result
    })
  })
  login()
}
function sendMessage (msg) {
  ifm.contentWindow.postMessage(msg, '*')
}
function get (method, url, fn) {
  var xhr = new XMLHttpRequest()
  xhr.open(method, url)
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var obj = JSON.parse(xhr.responseText)
      fn(obj)
    }
  }
  xhr.onerror = function () {}
  xhr.send()
}
function login () {
  var redirectUrl = chrome.identity.getRedirectURL()
  chrome.identity.launchWebAuthFlow({
    'url': 'https://api.weibo.com/oauth2/authorize?client_id=2212117607&redirect_uri=' + redirectUrl + '&response_type=code&scope=email',
    'interactive': true
  }, (redirect_url) => {
    var code = redirect_url.split('?')[1].split('=')[1]
    get('POST', 'https://api.weibo.com/oauth2/access_token?client_id=2212117607&client_secret=4b5792fcf14b3007c47d248b2ada0c00&grant_type=authorization_code&redirect_uri=' + redirectUrl + '&code=' + code, (obj) => {
      get('GET', 'https://api.weibo.com/2/users/show.json?access_token=' + obj.access_token + '&uid=' + obj.uid, (obj) => {
        console.log(obj)
      })
    })
  })
}
